// pages/plug/plug.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    xlb_key: 'QCIC82jD9e6JLK0OZcJW1mOB7C5v7QiR1537447029', // xlb_key 是一个动态的加密字符串
    source_user: '', // 上级用户的openid
    eventkey: '', // 活动编号
    join_type: 0, // 活动参与类型 0 -- 扫码, 1 -- 好友分享

    userInfo: {}, // 用户基本信息
    activity:  {}, // 活动
    use_able: true, // 活动是否可用
    errmsg: "", // 提示信息
    details_images: [],

    user_activity: {}, // 用户参与活动的数据
    dianzanBoxShowHide: 'none',
    supporters_head: [],

    price: 0,
    totalActivityUser: 0,
    top_image_width: (wx.getSystemInfoSync().windowWidth * 0.8177083) + 'px',
    shareBoxShowStatus: 'none',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    endtime: {},

    friendShareStatus: "none",

    form_id_arr: [],

    activity_end_status: 1

    // fontSize: 30
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let source_user = '';
    let eventkey = '';
    let _this = this;
    if (decodeURIComponent(options.scene).indexOf('_') != -1) {
      let scene = decodeURIComponent(options.scene);
      eventkey = scene.split('_')[0];
      source_user = scene.split('_')[1];
    }
    else {
      source_user = options.serial_no;
      eventkey = options.eventkey || decodeURIComponent(options.scene);
    }

    // 判断用户打开活动页面的方式
    if (source_user != undefined && eventkey != undefined) {
      // 用户通过好友的分享进来的（也有可能是自己的分享进来的）
      // 显示点赞弹出框
      this.setData({
        join_type: 1,
        source_user,
        eventkey
      })
    }
    else {
      this.setData({
        join_type: 0,
        source_user: source_user == undefined ? "" : source_user,
        eventkey: eventkey == undefined ? "" : eventkey
      })
    }

    this.setData({
      activity: wx.getStorageSync('activity_' + eventkey) ? wx.getStorageSync('activity_' + eventkey) : {},
      user_activity: wx.getStorageSync('user_activity_' + eventkey) ? wx.getStorageSync('user_activity_' + eventkey) : {},
      activity_end_status: wx.getStorageSync('activity_end_status_' + eventkey) ? wx.getStorageSync('activity_end_status_' + eventkey) : 1
    })
    
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              _this.dealUserInfo(res);
            }
          })
        }
        else {
          if (_this.data.join_type == 1) {
            _this.setData({
              dianzanBoxShowHide: 'block'
            })
          }
        }
      }
    })
  },

  /**
   * 第一次授权登陆
   */
  bindGetUserInfo: function (e) {
    this.dealUserInfo(e.detail);
  },

  /**
   * 处理用户授权登陆信息
   */
  dealUserInfo: function (res) {

    console.log(1111);
    let _this = this;
    let eventkey = _this.data.eventkey;
    let source_user = _this.data.source_user;
    let join_type = _this.data.join_type;
    let xlb_key = _this.data.xlb_key;
    let userInfo = res.userInfo;
    let encryptedData = res.encryptedData;
    let iv = res.iv;
    let signature = res.signature;
    _this.setData({
      userInfo
    })

    console.log(userInfo)

    wx.login({
      success(res) {
        console.log(res);
        let code = res.code;
        // 获取用户信息（创建用户）
        wx.request({
          url: 'https://mini.xiaoliebian.com/api/mini/mini_set_userinfo',
          method: 'POST',
          data: {
            eventkey,
            xlb_key,
            userInfo,
            source_user,
            encryptedData,
            join_type,
            iv,
            code
          },
          success(res) {
            let data = res.data;
            let supporters_head = data.supporters_head;
            if (supporters_head.length < 24) {
              let len = 24 - supporters_head.length;
              for (let i = 0; i < len; i++) {
                supporters_head.push('https://mini.xiaoliebian.com/public/mini/public/icon/head.png');
              }
            }
            else {
              supporters_head = supporters_head.slice(0, 24);
            }
            data.supporters_head = supporters_head;
            _this.setData({
              user_activity: data,
              supporters_head: supporters_head
            })

            wx.setStorageSync('user_activity_'+eventkey, data);
            if (data.serial_no == _this.data.source_user || parseInt(data.is_support, 10) == 1) {
              _this.setData({
                dianzanBoxShowHide: 'none'
              })
            }
            else {
              _this.setData({
                dianzanBoxShowHide: 'block'
              })
            }
          }
        })
      }
    })

    // 获取活动信息 使用缓存
    wx.request({
      url: 'https://mini.xiaoliebian.com/api/mini/mini_get_activity',
      data: {
        eventkey,
        xlb_key
      },
      success (res) {
        res = res.data;
        if (parseInt(res.code, 10) == 500) {
          wx.showToast({
            title: res.errmsg,
            icon: 'success',
            duration: 3000
          })
          _this.setData({
            use_able: false,
            errmsg: res.errmsg
          })
          return;
        }
        
        if (parseInt(res.activity.activity_end_type, 10) == 0) {
          let end = Date.parse(new Date(res.activity.activity_end_time)) || Date.parse(new Date(res.activity.activity_end_time.replace(/-/g, '/')));
          let intervalId = setInterval(function () {
            let now = Date.parse(new Date());
            let time_len = end - now;
            if (time_len < 0) {
              wx.showToast({
                title: "活动已经结束",
                icon: 'success',
                duration: 3000
              })
              clearInterval(intervalId);
              return
            }
            let hour_timestamp = 3600;
            let minute_timestamp = 60;
            let hour = Math.floor(time_len / 1000 / hour_timestamp);
            let minute = Math.floor((time_len / 1000 - hour * hour_timestamp) / minute_timestamp);
            let second = Math.floor(time_len / 1000 - hour * hour_timestamp - minute * minute_timestamp)
            _this.setData({
              endtime: {
                hour,
                minute,
                second
              }
            })
          }, 1000)
        }
        else {
          if (parseInt(res.activity.spread_end_award, 10) == 0) {
            wx.showToast({
              title: "活动已经结束",
              icon: 'success',
              duration: 3000
            })
          }
        }

        _this.setData({
          activity: res.activity,
          details_images: res.activity.details_images,
          totalActivityUser: res.count_all,
          activity_end_status: res.activity.activity_end_type
        })
        wx.setStorageSync('activity_end_status_' + eventkey, res.activity.activity_end_type)
        wx.setStorageSync('activity_' + eventkey, res.activity);
      }
    })
  },

  navigatorToBangdan: function () {
    let _this = this;
    wx.navigateTo({
      url: '../xlb_ranking/ranking?eventkey=' + _this.data.activity.spread_number
    })
  },

  /**
   * 获取formID
   */
  submitInfo: function (e) {
    let form_id = e.detail.formId;
    let from_id_array = this.data.form_id_arr;
    from_id_array.push(form_id);
    this.setData({
      form_id_arr: from_id_array
    })
  },

  /**
   * 保存formID
   */
  saveFormId: function () {
    let _this = this;
    let form_id_array = this.data.form_id_arr;
    let xlb_key = this.data.xlb_key;
    let openid = this.data.user_activity.openid;
    let eventkey = this.data.eventkey;
    wx.request({
      url: 'https://mini.xiaoliebian.com/api/mini/mini_save_form_id',
      method: 'POST',
      data: {
        form_id_array,
        xlb_key,
        openid,
        eventkey
      },
      success (res) {
        if (parseInt(res.data.code, 10) == 200) {
          _this.setData({
            form_id_arr: []
          })
        }
      }
    })
  },

  /**
   * 底部分享页面的显示隐藏控制
   */
  hideShareBox: function () {
    this.setData({
      shareBoxShowStatus: 'none'
    })
  },

  showShareBox: function () {
    this.setData({
      shareBoxShowStatus: 'block'
    })
  },

  hideFriendShareBox: function () {
    this.setData({
      friendShareStatus: 'none'
    })
  },

  hideDianzan: function () {
    this.setData({
      dianzanBoxShowHide: 'none'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.saveFormId();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.saveFormId();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let _this = this;
    let group_share_text = _this.data.activity.group_share_text;
    group_share_text = group_share_text.replace(/\{nickname\}/g, _this.data.userInfo.nickName);
    return {
      title: group_share_text,
      path: 'pages/xlb_plug/plug?eventkey=' + _this.data.activity.spread_number + '&serial_no=' + _this.data.user_activity.serial_no,
      imageUrl: _this.data.activity.group_litpic
    }
  },

  onShareQuanziMessage: function () {
    let _this = this;
    let eventkey = _this.data.eventkey;
    let xlb_key = _this.data.xlb_key;
    let serial_no = _this.data.user_activity.serial_no;

    wx.request({
      url: 'https://mini.xiaoliebian.com/api/mini/generate_share_image',
      method: 'POST',
      data: {
        eventkey,
        xlb_key,
        serial_no
      },
      success (res) {
        res = res.data;
        if (parseInt(res.code) == 200) {
          let url = "https://mini.xiaoliebian.com" + res.url;
          console.log('upload url', url);
          wx.downloadFile({
            url: url,
            success(res) {
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success() {
                  wx.hideLoading()
                  _this.setData({
                    friendShareStatus: "block"
                  })
                },
                fail(res) {
                  console.log(res);
                }
              })
            },
            fail(res) {
              console.log(res);
            }
          })
          return;
        }

        wx.showToast({
          title: res.errmsg,
          icon: 'success',
          duration: 3000
        })
      }
    })
  },

  setClipboardData: function () {
    let _this = this;
    wx.setClipboardData({
      data: _this.data.activity.friends_share_text,
      success: function (res) {
        _this.setData({
          friendShareStatus: "none"
        })

        wx.showToast({
          title: "复制成功",
          icon: 'success',
          duration: 3000
        })
      }
    })
  }
})